package com.syni.mdd.yhd.common.all.controller.protect.alipay;


import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.syni.mdd.sjb.common.component.utils.common.annotations.CheckParams;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.yhd.common.all.config.pay.alipay.AlipayConfig;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.constants.ResultMsg;
import com.syni.mdd.yhd.common.all.controller.pay.wxPay.WxPayController;
import com.syni.mdd.yhd.common.all.entity.BmsDxOrder;
import com.syni.mdd.yhd.common.all.service.BmsDxOrderService;
import com.syni.mdd.yhd.common.all.service.pay.aiPay.AliPayService;
import com.syni.mdd.yhd.common.all.service.pay.aiPay.AlipayServiceImpl;
import com.syni.mdd.sjb.common.component.utils.common.utils.ParamsMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;


@RestController
@RequestMapping("/aliPay")
public class AliPayAppController {

    @Autowired
    private AliPayService aliPayService;

    @Autowired
    BmsDxOrderService bmsDxOrderService;

    @Autowired
    WxPayController wxPayController;

    @Autowired
    @Qualifier("oldAliPayConfig")
    AlipayConfig oldAliPayConfig;

    @Autowired
    @Qualifier("aliPayConfig")
    AlipayConfig alipayConfig;

    private final Logger log = LoggerFactory.getLogger(getClass());


    /**
     * 发起支付
     * @param merchantId 个体商户号
     * @param subject 支付标题
     * @param body 支付内容
     * @param totalAmt 支付金额（元）
     * @return
     */
    @CheckParams(params = {"orderId","orderNo"})
    @PostMapping("/prepay")
    @ResponseBody
    public Map<String,Object> prepay(@RequestBody Map<String,Object> paramsMap) {
        Map<String, Object> resultMap = new HashMap<>();
        Integer orderId = Integer.parseInt(paramsMap.get("orderId").toString());
        String orderNo = paramsMap.get("orderNo").toString();
        //检验订单号和订单id是否一致
        Optional<BmsDxOrder> bmsDxOrderOptional = bmsDxOrderService.getBaseDao().findById(orderId);
        if (!bmsDxOrderOptional.isPresent()) {
            return ResultMapHelper.result(ResultCode.CODE_ORDER_NO_EXIST, ResultMsg.CODE_ORDER_NO_EXIST);
        }
        BmsDxOrder bmsDxOrder = bmsDxOrderOptional.get();
        if (!bmsDxOrder.getOrderNo().equals(orderNo)) {
            return ResultMapHelper.result(ResultCode.CODE_ORDER_ID_NOMATCH_NO, ResultMsg.CODE_ORDER_ID_NOMATCH_NO);
        }
        Map<String, Object> checkMap = bmsDxOrderService.checkOrderCanPay(bmsDxOrder);
        if (!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())) {
            return checkMap;
        }
        String totalAmt = bmsDxOrder.getActualConsum().toString();
        log.info("下单动用的支付宝配置：" + JSON.toJSONString(alipayConfig));
        try {
            // 这个东西必备
            AlipayClient alipayClient = new DefaultAlipayClient(
                    alipayConfig.getServerUrl(),
                    alipayConfig.getAppid(),
                    alipayConfig.getPrivateKey(),
                    "json",
                    "UTF-8",
                    alipayConfig.getPublicKey(),
                    "RSA2");
            // 发起App支付请求
            AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
            // 订单描述
            model.setBody(AlipayServiceImpl.PAY_DEFAULT_DESC);
            // 订单标题
            model.setSubject(aliPayService.getOrderSubject(bmsDxOrder));
            // 商户订单号 就是商户后台生成的订单号
            model.setOutTradeNo(orderNo);
            // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天 (屁股后面的字母一定要带，不然报错)
            model.setTimeoutExpress("30m");
            // 订单总金额 ，默认单位为元，精确到小数点后两位，取值范围[0.01,100000000]
            model.setTotalAmount(totalAmt);
            // 销售产品码 不必填
            model.setProductCode("QUICK_MSECURITY_PAY");
            request.setBizModel(model);
            request.setNotifyUrl(alipayConfig.getCallBackUrl());
            // 通过api的方法请求阿里接口获得反馈
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            if (response.isSuccess()) {
                log.info("支付调用成功");
                String result = response.getBody();
                resultMap.put("payCredent", result);
                bmsDxOrder.setPayWay(Constants.ALI_PAY);
                bmsDxOrderService.getBaseDao().save(bmsDxOrder);
                return ResultMapHelper.success(resultMap, ResultMsg.MSG_GET_SUCCESS);
            }
        } catch (Exception e) {
            log.error("aliPayArouse Error:",e);
        }
        return ResultMapHelper.result(ResultCode.CODE_PAY_ID_GET_FIAR, "支付凭证获取失败");

    }

    /**
     * @Description 用户端退款接口
     * @Author: cfx
     * @Date: 2019/8/2
     */
    @PostMapping("refundOrder")
    @CheckParams(checkAuth = true,params = {"orderId","groupBuyUseIds"})
    public synchronized Map<String,Object> refundOrder(@RequestBody ParamsMap paramsMap) {
        Map<String,Object> resultMap;
        try {
            resultMap =  bmsDxOrderService.refundOrder_v3(paramsMap);
        }catch (Exception e){
            log.info(e.toString());
            resultMap = ResultMapHelper.result(ResultCode.CODE_ORDER_REFUND_TOO_LOGN,"退款超时,请重试");
        }
        return resultMap;
    }


}
